<?php

namespace backend\models\search;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use backend\models\Photo;

/**
 * PhotoSearch represents the model behind the search form about `backend\models\Photo`.
 */
class PhotoSearch extends Photo
{

	//添加属性 重写attribute方法 增加新添的属性
	public function attributes() {
		return array_merge(parent::attributes(),['authorName']);

	}

	/**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'uid'], 'integer'],
            [['authorName','brife', 'img', 'iso', 'status', 'type', 'make', 'lens', 'model', 'exposer', 'fnumber', 'created_at', 'updated_at'], 'safe'],
            [['flength'], 'number'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = Photo::find();

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        // grid filtering conditions
        $query->andFilterWhere([
            'photo.id' => $this->id,
            'uid' => $this->uid,
            'flength' => $this->flength,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
        ]);

        $query->andFilterWhere(['like', 'brife', $this->brife])
            ->andFilterWhere(['like', 'img', $this->img])
            ->andFilterWhere(['like', 'iso', $this->iso])
            ->andFilterWhere(['like', 'photo.status', $this->status]) //防止出现歧义，导致查询失败
            ->andFilterWhere(['like', 'type', $this->type])
            ->andFilterWhere(['like', 'make', $this->make])
            ->andFilterWhere(['like', 'lens', $this->lens])
            ->andFilterWhere(['like', 'model', $this->model])
            ->andFilterWhere(['like', 'exposer', $this->exposer])
            ->andFilterWhere(['like', 'fnumber', $this->fnumber]);

		//联结查询，用于搜索用户名
        $query->join('INNER JOIN','user','photo.uid = user.id');
		$query->andFilterWhere(['like','user.username',$this->authorName]);

        $dataProvider->sort->attributes['authorName']=[
        	'asc'=>['user.username'=>SORT_ASC],
	        'desc'=>['user.username'=>SORT_DESC],
        ];


        //设置默认排序
        $dataProvider->sort->defaultOrder=[
        	'created_at'=>SORT_DESC,
        ];


        return $dataProvider;
    }
}
